<?php

namespace App\Http\Controllers\Admin;

use App\Api\Sms\SmsClient;
use App\Http\Controllers\Controller as BaseController;
use App\Repository\Admin\AdminUsersRepository;
use App\Repository\Order\OrderExportRepository as model;
use App\Repository\Order\OrderLogRepository as logModel;
use App\Repository\Shop\SuppilerRepository as supp;
use App\Repository\Sms\SmsSendLogRepository;
use App\Repository\Sms\SmsTmpRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

// 分销商
class OrderExportController extends BaseController
{
    private $repoist;
    private $disModel;
    private $logModel;

    public function __construct(model $model, supp $supp, logModel $logModel)
    {
        $this->repoist = $model;
        $this->disModel = $supp;
        $this->logModel = $logModel;
    }

    public function store(Request $request)
    {
        $request->offsetSet('name', $request->get('export_name'));
        $params = $request->all();
        if (!empty($params['user'])) {
            unset($params['user']);
        }
        $request->offsetSet('parame', json_encode($params));
        if ($request->has('shop_id')) {
            $request->offsetSet('shop_id', 0);
        }
        return $this->repoist->add($request);
    }

    public function index(Request $request)
    {
        $where = [];
        if (!empty($request->get('status'))) {
            $where['where']['status'] = $request->get('status');
        }
        if (!empty($request->get('user')->role_id) && $request->get('user')->role_id != 1 && empty($request->get('is_dist'))) {
            $where['where']['shop_id'] = $request->get('user')->shop_id;
        }
        if (empty($request->get('user')->role_id)) {
            $where['where']['shop_id'] = $request->get('user')->shop_id;
        }
        if (!empty($request->get('is_dist'))) {
            $where['like']['shop_str'] = $request->get('user')->shop_id;
        }
        if (!empty($request->get('shop_id'))) {
            $where['like']['shop_id_str'] = $request->get('user')->shop_id . '.' . $request->get('shop_id');
        }
        if (!empty($request->get('orderno'))) {
            $where['where']['orderno'] = trim($request->get('orderno'), ' ');
        }
        if (!empty($request->get('pay_identity'))) {
            $where['where']['pay_identity'] = trim($request->get('pay_identity'), ' ');
        }
        if (!empty($request->get('sup_orderno'))) {
            $where['where']['sup_orderno'] = $request->get('sup_orderno');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('dist_orderno'))) {
            $where['where']['dist_orderno'] = $request->get('dist_orderno');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('iccid'))) {
            $where['where']['iccid'] = $request->get('iccid');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('express_number'))) {
            $where['where']['express_number'] = $request->get('express_number');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('contact_phone'))) {
            $where['where']['contact_phone'] = $request->get('contact_phone');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('contact_name'))) {
            $where['where']['contact_name'] = $request->get('contact_name');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('number'))) {
            $where['like']['name'] = $request->get('number');
        }
        //时间验证
        if (!empty($request->get('dateRange'))) {
            // $time = $request->get('dateRange');
            $where['between'] = ['created_at' => $request->get('dateRange')];
        }
        // var_dump($where);
        $where['limit']['start'] = ($request->get('pageNum') - 1) * $request->get('pageSize');
        $where['limit']['number'] = $request->get('pageSize');
        // var_dump($where);
        $data = $this->repoist->index($where);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => &$v) {
                $v['path'] = '';
            }
        }
        return $data;
    }

    public function sendYzm(Request $request)
    {
        if (empty($request->get('id'))) {
            return $this->returnMsg(100, '请传递参数');
        }
        $id = $request->get('id');

        if (empty($request->get('user')->shop_id)) {
            return $this->returnMsg(101, '请登录');
        }
        $shop_id = $request->get('user')->shop_id;
        $shopArr = DB::table('admin_users')->where(['id' => $shop_id])->first();
        if (!$shopArr) {
            return $this->returnMsg(101, '未查询到店铺信息');
        }
        if (empty($shopArr->phonenumber)) {
            return $this->returnMsg(103, '请联系店主,前去个人中心添加手机号');
        }
//        $model = new TransferSms();
        $num = mt_rand(000000, 999999);
        // $content = '【验证码】本次导出密码:' . $num;
//        $content = '【导出验证码】本次导出密码:' . $num . '，请勿告诉其他人，退订回T';
        // $phone = '15225070393';
        $phone = $shopArr->phonenumber;
        //将验证码存入缓存
        Cache::put($id . 'yzm' . $shop_id, $num);

        $Repository = new SmsTmpRepository();
        $row = $Repository->unifiedGetOne(['name' => '功能操作'], ['id', 'tpl_id', 'name', 'content']);
        if (empty($row)) {
            return [
                'code' => 1,
                'msg' => '请先审核一个名为:功能操作的模板后再操作',
            ];
        }
//            print_r($row);
        $SmsApi = new SmsClient();
        $tplParamsData = ['code' => $num];
        $res = $SmsApi->sendSmsByTpl($phone, $row['tpl_id'], $row['type'], $row['content'], $tplParamsData);
        $content = $SmsApi->parseTplContent($row['content'], $tplParamsData);
//            记录发送日志
//            $res['data']['smsId'] = '1123213528019378904593';
        $LogRepository = new SmsSendLogRepository();
        $LogRepository->add([
            'sms_id' => $res['data']['smsId'],
            'sms_tmp_name' => $row['name'],
            'sms_tmp_id' => $row['id'],
            'content' => $content,
            'order_id' => 0,
            'shop_id' => $shop_id
        ]);
        $res = [
            'code' => 200,
            'msg' => '验证码发送成功,请及时输入！',
            'data' => []
        ];
        return $res;
        // return $this->returnMsg(200, '发送成功');
    }

    public function getPath(Request $request)
    {
        if (empty($request->get('id'))) {
            return $this->returnMsg(100, '请传递参数');
        }
        if (empty($request->get('cache')) && empty($request->get('exp_passwd'))) {
            return $this->returnMsg(101, '请输入验证码或导出密码');
        }
        $cachey = $request->get('cache');
        $id = $request->get('id');
        $expPasswd = $request->get('exp_passwd');

        if (empty($request->get('user')->shop_id)) {
            return $this->returnMsg(101, '请登录');
        }
        // 验证码验证
        $shop_id = $request->get('user')->shop_id;
        $cache = Cache::get($id . 'yzm' . $shop_id);
        $isTrue = true;
        // var_dump($cache, 1111111);
        if (empty($cache) || $cache != $cachey) {
            if (!empty($cachey)) {
                $isTrue = false;
                return $this->returnMsg(109, '短信验证码不正确');
            }
        }
        // 导出密码验证
        if ($isTrue) {
            $model = new AdminUsersRepository();
            $userId = $request->get('user')->id;
            $resUser = $model->getOne(['id' => $userId, 'shop_id' => $shop_id]);
            if (!$resUser) {
                return $this->returnMsg(104, '未查询到店铺信息');
            }
            $resPasswd = $model->verifyPasswd($expPasswd, $resUser->exp_passsalt);
//            print_r($request['user']);
            if ($resPasswd != $resUser->exp_password) {
                return $this->returnMsg(105, '导出密码不正确');
            }
        }

        // 验证
        $res = $this->repoist->getOne(['id' => $id, 'shop_id' => $shop_id], ['path']);
        if (!$res) {
            return $this->returnMsg(105, '该订单不是自己的订单不能下载');
        }
        if (empty($res->path)) {
            return $this->returnMsg(104, '文件不存在,请联系管理员');
        }
        Cache::put($id . 'yzm' . $shop_id, 0, 100);
        return $this->returnMsg(200, '查询成功', $res);
    }
}
